package second.thread.threadlocaltest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: heweiwei
 * @Date: 3/16/25 PM2:30
 * @Description:
 */
public class ThreadLocalRemoveTest {

    private final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void add() {
        threadLocal.set(threadLocal.get() + 1);
    }

    public static void main(String[] args) {
        ThreadLocalRemoveTest test = new ThreadLocalRemoveTest();
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        try {
            for (int i = 0; i < 10; i++) {
                executorService.submit(() -> {
                    try {
                        System.out.println(Thread.currentThread().getName() + " before:" + test.threadLocal.get());
                        test.add();
                        System.out.println(Thread.currentThread().getName() + " after:" + test.threadLocal.get());
                    } finally {
                        // 手动remove,如果业务逻辑执行完毕没有及时remove,那么下一次执行业务逻辑,如果还是此线程就回读取到上一次线程的结果
                        test.threadLocal.remove();
                    }
                });
            }
        } finally {
            executorService.shutdown();
        }
    }
}
